package com.example.sso.server.controller;

import com.example.sso.server.entity.ClientApp;
import com.example.sso.server.entity.Token;
import com.example.sso.server.repository.ClientAppRepository;
import com.example.sso.server.repository.TokenRepository;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class TokenController {

    @Autowired
    private ClientAppRepository clientAppRepository;
    
    @Autowired
    private TokenRepository tokenRepository;
    
    private final Gson gson = new Gson();

    @PostMapping(value = "/oauth/token", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getToken(
            @RequestParam("client_id") String clientId,
            @RequestParam("client_secret") String clientSecret,
            @RequestParam("code") String code,
            @RequestParam("grant_type") String grantType,
            @RequestParam("redirect_uri") String redirectUri) {
        
        // 验证客户端ID和密钥
        ClientApp clientApp = clientAppRepository.findByClientId(clientId);
        if (clientApp == null || !clientApp.getClientSecret().equals(clientSecret)) {
            return buildErrorResponse("unauthorized_client", "无效的客户端凭证");
        }
        
        // 验证授权码
        if (!tokenRepository.isValidCode(code)) {
            return buildErrorResponse("invalid_grant", "无效的授权码");
        }
        
        // 验证grant_type
        if (!"authorization_code".equals(grantType)) {
            return buildErrorResponse("unsupported_grant_type", "不支持的授权类型");
        }
        
        // 验证redirect_uri
        if (!clientApp.getRedirectUri().startsWith(redirectUri.split("\\?")[0])) {
            return buildErrorResponse("invalid_request", "重定向URI不匹配");
        }
        
        // 移除已使用的授权码
        tokenRepository.removeCode(code);
        
        // 生成访问令牌
        Token token = tokenRepository.generateToken();
        
        // 返回令牌信息
        Map<String, Object> response = new HashMap<>();
        response.put("access_token", token.getAccessToken());
        response.put("token_type", token.getTokenType());
        response.put("expires_in", token.getExpiresIn());
        return gson.toJson(response);
    }
    
    private String buildErrorResponse(String error, String errorDescription) {
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("error", error);
        if (errorDescription != null) {
            errorResponse.put("error_description", errorDescription);
        }
        return gson.toJson(errorResponse);
    }
}
    